<script lang="ts">
import { ref } from 'vue'
import axios from 'axios'

// 定义消息类型
interface Message {
  type: 'text' | 'audio'
  content: string
}

export default {
  setup() {
    const messages = ref<Message[]>([]) // 存储聊天消息
    const isRecording = ref(false) // 是否正在录音
    const mediaRecorder = ref<MediaRecorder | null>(null) // 媒体录音器
    const audioChunks = ref<Blob[]>([]) // 存储音频数据

    // 开始录音
    const startRecording = async () => {
      audioChunks.value = [] // 清空之前的录音数据
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      mediaRecorder.value = new MediaRecorder(stream)

      mediaRecorder.value.ondataavailable = (event: BlobEvent) => {
        audioChunks.value.push(event.data)
      }

      mediaRecorder.value.onstop = handleRecordingStop
      mediaRecorder.value.start()

      isRecording.value = true
    }

    // 停止录音
    const stopRecording = () => {
      mediaRecorder.value?.stop()
      isRecording.value = false
    }

    // 处理录音停止后的操作
    const handleRecordingStop = () => {
      const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' })
      const audioUrl = URL.createObjectURL(audioBlob)
      messages.value.push({ type: 'audio', content: audioUrl })

      // 上传音频文件
      uploadAudio(audioBlob)
    }

    // 上传音频到后端
    const uploadAudio = async (audioBlob: Blob) => {
      const formData = new FormData()
      formData.append('voiceFile', audioBlob, 'voice.wav')

      try {
        const response = await axios.post('/desktop/voiceControl', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        messages.value.push({ type: 'text', content: response.data }) // 假设返回的是转换后的文字
      } catch (error) {
        console.error('上传失败:', error)
      }
    }

    return {
      messages,
      isRecording,
      startRecording,
      stopRecording
    }
  }
}
</script>

<template>
  <router-view></router-view>
</template>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

.chat-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.messages {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 10px;
}

.message {
  margin-bottom: 10px;
}

.message-text {
  background-color: #e0e0e0;
  padding: 10px;
  border-radius: 5px;
  display: inline-block;
}

.message-audio audio {
  max-width: 100%;
  margin-top: 5px;
}

.controls {
  display: flex;
  justify-content: center;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  margin: 0 10px;
  border-radius: 5px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
